package com.mnnu.controller;

import com.google.code.kaptcha.Producer;
import com.mnnu.common.config.RuoYiConfig;
import com.mnnu.common.constant.CacheConstants;
import com.mnnu.common.domain.AjaxResult;
import com.mnnu.common.redis.RedisCache;
import com.mnnu.common.utils.sign.Base64;
import com.mnnu.common.utils.uuid.IdUtils;
import com.mnnu.system.service.ISysConfigService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
public class CaptchaController {

    @Autowired
    public ISysConfigService sysConfigService;

    @Resource(name = "captchaProducer")
    public Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    public Producer captchaProducerMath;

    @Autowired
    public RedisCache redisCache;


    /**
     * 验证码获取
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCaptchaImage() {
        AjaxResult res = AjaxResult.success();
        // 判断当前是否开启验证码
        boolean status = sysConfigService.selectCaptchaEnabled();
        res.put("captchaEnable", status);
        // 若不开启验证码，则返回
        if (!status) {
            return res;
        }

        // 保存验证码，创建验证码键
        String capStr = null, code = null;
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        BufferedImage img = null;

        // 判断验证码类型
        String captchaType = RuoYiConfig.getCaptchaType();
        if ("math".equals(captchaType)) {
            // 生成math类型验证码
            String captchaText = captchaProducerMath.createText();
            // 分割题目和答案
            capStr = captchaText.substring(0, captchaText.indexOf("@"));
            code = captchaText.substring(captchaText.indexOf("@") + 1);
            // 将题目转为图片
            img = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            //TODO:生成char类型验证码
        }

        // 将验证码答案存入redis缓存
        redisCache.setCacheObject(verifyKey, code, 5, TimeUnit.MINUTES);

        // 流转换并返回
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(img, "jpg", os);
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }
        res.put("img", Base64.encode(os.toByteArray()));
        res.put("uuid", uuid);

        return res;
    }
}
